package com.z_talk.client.view;

import com.z_talk.client.core.ClientSender;
import com.z_talk.core.enums.RequestEnum;
import com.z_talk.core.message.RequestMessage;
import com.z_talk.core.model.LoginModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;

public class LoginView {
    private JButton loginBut;
    private JButton registerBut;
    private JTextField userId;
    private JPasswordField password;
    private JPanel formPanel;
    private JPanel formLabel;
    private JLabel nicknameLabel;
    private JLabel passwordLabel;
    private JPanel loginPanel;

    private static ClientSender clientSender;

    public LoginView() {
        this.clientSender = ClientSender.getInstance();
        loadData();
        init();
    }

    private void loadData() {
    }

    private void init(){
        JFrame jFrame = new JFrame("登录");
        jFrame.setContentPane(this.loginPanel);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(400,250);
        int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        int y = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        jFrame.setLocation((x - jFrame.getWidth()) / 2, (y-jFrame.getHeight())/ 2);
        jFrame.setResizable(false);

        userId.requestFocus();

        // 添加事件
        registerBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new RegisterView();
            }
        });
        loginBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userIdText = userId.getText();
                String passwordStr = new String(password.getPassword());
                LoginModel loginVO = new LoginModel(userIdText,passwordStr);
                RequestMessage message = new RequestMessage();
                message.setMessageType(RequestEnum.LOGIN_REQUEST);
                Map<String,Object> attribute = new HashMap<>();
                attribute.put(RequestEnum.LOGIN_REQUEST.getAttr(), loginVO);
                message.setAttribute(attribute);
                try {
                    clientSender.sendMsg(message);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
                jFrame.dispose();
            }
        });
    }

}
